package com.zqxq.lottery.controller.user;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.zqxq.common.constant.Result;
import com.zqxq.common.enums.CodeEnum;
import com.zqxq.common.utils.StrUtils;
import com.zqxq.lottery.common.constant.HuaYangConstant;
import com.zqxq.lottery.config.YmlConfig;
import com.zqxq.lottery.controller.pay.IAlipayService;
import com.zqxq.lottery.entity.po.sys.SysConfigPO;
import com.zqxq.lottery.entity.po.user.*;
import com.zqxq.lottery.entity.vo.user.UserInfoVO;
import com.zqxq.lottery.mapper.sys.SysConfigMapper;
import com.zqxq.lottery.mapper.user.UserFundsMapper;
import com.zqxq.lottery.mq.Sender;
import com.zqxq.lottery.service.user.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;


@RestController
@Slf4j
@RequestMapping("/userFunds")
public class UserFundsController extends UserBaseController{

    private String ckey = "ZQXQ_DRAWCASH_CONFIG";

    private String msg_deposit = "您申请的 %s 元提现申请成功，24小时之内到账，请前往支付宝查看！";

    private String msg_deposit_error = "您好，您申请的 %s 元提现失败，余额不足，请查看";

    @Autowired
    private IUserFundsService userFundsService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserAlipayService userAlipayService;

    @Autowired
    private IUserWechatService userWechatService;

    @Autowired
    private IUserCashService userCashService;

    @Autowired
    private IAlipayService alipayService;

    @Autowired
    private IUserMsgService userMsgService;

    @Autowired
    private UserFundsMapper userFundsMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static String DRAWCASH = "DRAWCASH_";
    private static String BALANCECONSUME = "BALANCECONSUME_";
    private static String ALIPAYCONSUME = "ALIPAYCONSUME_";
    private static String WECHATCONSUME = "WECHATCONSUME_";

    @Autowired
    private YmlConfig ymlConfig;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private Sender sender;
    private String moblies = "13452461530,17132303462,15334563553,15334560300,13048470746,13452461740,13140315294";


    /**
     * 充值
     * @param userId
     * @param money
     * @return
     */
    @PostMapping("/recharge")
    public Result recharge(Long userId, BigDecimal money, Integer payWay, String payAccount, Long cashId){
        Result rs = new Result();
        try{
            if(userId == null || money == null || payWay == null || payAccount == null){
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
            } else {
                money = money;
                boolean re = userFundsService.saveRechargeOrConsume(userId, money, 1, payWay, payAccount, cashId);
                if(!re){
                    rs.setCode(CodeEnum.FAIL.getCode());
                    rs.setMsg(CodeEnum.FAIL.getMsg());
                }
            }
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL_100005.getCode());
            rs.setMsg(CodeEnum.FAIL_100005.getMsg());
            log.error("UserCash Page  Error:",e);
        }
        return rs;
    }

    /**
     * 余额消费
     * @param userId
     * @param money
     * @return
     */
    @PostMapping("/balanceConsume")
    public Result balanceConsume(Long userId, BigDecimal money, Long orderId, String payPassword,Long couponId){
        Result rs = new Result();
        String key = BALANCECONSUME+userId;
        String value = stringRedisTemplate.opsForValue().get(key);
        if(StrUtils.isNotEmpty(value)){
            rs.setCode(10012);
            rs.setMsg("你的付款订单正在处理中，请稍后操作！");
            return rs;
        }
        try{
            stringRedisTemplate.opsForValue().set(key,key);
            if(userId == null || money == null || StrUtils.isEmpty(payPassword)){
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
            } else {
                UserInfoPO userInfoPO = userInfoService.selectById(userId);
                if(userInfoPO == null){
                    rs.setCode(CodeEnum.FAIL_100002.getCode());
                    rs.setMsg(CodeEnum.FAIL_100002.getMsg());
                    return rs;
                }
                if(StrUtils.isEmpty(userInfoPO.getPay_password())){
                    rs.setCode(10006);
                    rs.setMsg("请设置支付密码！");
                    return rs;
                }
                if(!payPassword.equalsIgnoreCase(userInfoPO.getPay_password())){
                    rs.setCode(10007);
                    rs.setMsg("支付密码错误！");
                    return rs;
                }
                boolean flag = userFundsService.saveBalanceConsume(userInfoPO, money, orderId,couponId);
                if(flag){
                    //支付成功 发起出票
                    /*if(!moblies.contains(userInfoPO.getMobile()))
                        sender.send(HuaYangConstant.MQ_HUAYANG_ORDER_BET,orderId);*/
                }
                else{
                    rs.setCode(10016);
                    rs.setMsg("余额不足！");
                    return rs;
                }
            }
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL_100005.getCode());
            rs.setMsg(CodeEnum.FAIL_100005.getMsg());
            log.error("UserCash Page  Error:",e);
        }finally {
            stringRedisTemplate.delete(key);
        }
        return rs;
    }

    /**
     * 支付宝消费
     * @param userId
     * @param money
     * @return
     */
    @PostMapping("/alipayConsume")
    public Result alipayConsume(Long userId, BigDecimal money, Long orderId, String alipayAccount,Long couponId,BigDecimal balance){
        Result rs = new Result();
        String key = ALIPAYCONSUME+userId;
        String value = stringRedisTemplate.opsForValue().get(key);
        if(StrUtils.isNotEmpty(value)){
            rs.setCode(10012);
            rs.setMsg("你的支付订单正在处理中，请稍后操作！");
            return rs;
        }
        try{
            stringRedisTemplate.opsForValue().set(key,key);
            if(userId == null || money == null || orderId == null || StrUtils.isEmpty(alipayAccount)){
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
            } else {
                UserInfoPO userInfoPO = userInfoService.selectById(userId);
                boolean flag = userFundsService.saveAlipayConsume(userInfoPO, money, orderId, alipayAccount,couponId,balance);
                if(flag){
                    //支付成功 发起出票
                    /*if(!moblies.contains(userInfoPO.getMobile()))
                        sender.send(HuaYangConstant.MQ_HUAYANG_ORDER_BET,orderId);*/
                }
            }
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL_100005.getCode());
            rs.setMsg(CodeEnum.FAIL_100005.getMsg());
            log.error("UserCash Page  Error:",e);
        }finally {
            stringRedisTemplate.delete(key);
        }
        return rs;
    }

    /**
     * 微信消费
     * @param userId
     * @param money
     * @return
     */
    @PostMapping("/wechatConsume")
    public Result wechatConsume(Long userId, BigDecimal money, Long orderId, String wechatAccount,Long couponId,BigDecimal balance){
        Result rs = new Result();
        String key = WECHATCONSUME+userId;
        String value = stringRedisTemplate.opsForValue().get(key);
        if(StrUtils.isNotEmpty(value)){
            rs.setCode(10012);
            rs.setMsg("你的支付订单正在处理中，请稍后操作！");
            return rs;
        }
        try{
            stringRedisTemplate.opsForValue().set(key,key);
            if(userId == null || money == null || orderId == null || StrUtils.isEmpty(wechatAccount)){
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
            } else {
                UserInfoPO userInfoPO = userInfoService.selectById(userId);
                boolean flag = userFundsService.saveWechatConsume(userInfoPO, money, orderId, wechatAccount,couponId,balance);
                if(flag){
                    //支付成功 发起出票
                    /*if(!moblies.contains(userInfoPO.getMobile()))
                        sender.send(HuaYangConstant.MQ_HUAYANG_ORDER_BET,orderId);*/
                }
            }
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL_100005.getCode());
            rs.setMsg(CodeEnum.FAIL_100005.getMsg());
            log.error("UserCash Page  Error:",e);
        }finally {
            stringRedisTemplate.delete(key);
        }
        return rs;
    }
    @PostMapping("/batchDrawCash")
    public Result drawCash(HttpServletRequest request) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.gt("balance",0);
        List<UserFundsPO> userFundsPOList = userFundsService.selectList(wrapper);
        for(UserFundsPO userFundsPO : userFundsPOList){
            UserInfoPO userInfoPO = userInfoService.selectById(userFundsPO.getUser_id());
            drawCash(request,userFundsPO.getUser_id(),userFundsPO.getBalance(),1,"",userInfoPO.getPay_password());
        }
        return new Result();
    }
    /**
     * 提现
     * @param userId
     * @param money
     * @return
     */
    @PostMapping("/drawCash")
    public Result drawCash(HttpServletRequest request, Long userId, BigDecimal money, Integer payWay, String payAccount, String payPassword){
        Result rs = new Result();
        rs.setMsg("提现申请成功，24小时之内到账！");
        SysConfigPO config = sysConfigMapper.getByKey(ckey);
        if(config == null || config.getStatus()==0){
            rs.setCode(10);
            rs.setMsg("提现功能暂用！");
            return rs;
        }
        try{
            UserInfoVO userInfoVO = userInfoService.getVO(userId);
            String enabled = userInfoVO.getEnabled();
            if("1".equals(enabled)){
                return new Result(10000,"抱歉，您的账户已被禁用,不能进行敏感操作！");
            }
            if(userId == null || money == null || payWay == null){
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
                return rs;
            }
            UserInfoPO userInfoPO = userInfoService.selectById(userId);
            if(userInfoPO == null){
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
                return rs;
            }
            if(StrUtils.isEmpty(userInfoPO.getReal_name()) || StrUtils.isEmpty(userInfoPO.getId_card())){
                rs.setCode(10050);
                rs.setMsg("该用户没有实名认证，请实名认证！");
                return rs;
            }
            if(StrUtils.isEmpty(userInfoPO.getPay_password())){
                rs.setCode(10006);
                rs.setMsg("请设置支付密码！");
                return rs;
            }
            if(!payPassword.equalsIgnoreCase(userInfoPO.getPay_password())){
                rs.setCode(10007);
                rs.setMsg("支付密码错误！");
                return rs;
            }

            if(payWay == 1){
                UserAlipayPO alipayPO = userAlipayService.selectById(userId);
                if(alipayPO == null || StrUtils.isEmpty(alipayPO.getAlipay_account())){
                    rs.setCode(10008);
                    rs.setMsg("请绑定支付宝账号！");
                    return rs;
                }
                //查询支付宝账号
                payAccount = alipayPO.getAlipay_account();
            } else if(payWay == 6){
                UserWechatPO userWechatPO = userWechatService.selectById(userId);
                if(userWechatPO == null || StrUtils.isEmpty(userWechatPO.getOpen_id())){
                    rs.setCode(10008);
                    rs.setMsg("请绑定微信账号！");
                    return rs;
                }
                //查询微信账号
                payAccount = userWechatPO.getOpen_id();
            } else {
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
                return rs;
            }
            int count = userCashService.getDrawCashCount(userId);
            if(count >= 3){//判断提现次数
                rs.setCode(10009);
                rs.setMsg("提现失败，每人每天最多可提现3次。");
                return rs;
            }
            if(money.doubleValue() < 10){
                rs.setCode(10010);
                rs.setMsg("提现失败，每人每次最少提现10元。");
                return rs;
            }
            if (money.doubleValue() > 5000){
                rs.setCode(10012);
                rs.setMsg("单笔提现金额不能大于5千。");
                return rs;
            }
            UserFundsPO userFundsPO = userFundsMapper.selectById(userId);
            if(userFundsPO.getBalance().compareTo(money.setScale(2,BigDecimal.ROUND_HALF_UP))<0){
                rs.setCode(10012);
                rs.setMsg("钱包余额不够！");
                return rs;
            }
            /*BigDecimal consumeTotalAmount = userFundsMapper.getTotalAmountByUserIdIn7Day(userId,0);  //7天内余额支付消费金额
            if(BigDecimal.ZERO.compareTo(consumeTotalAmount)==0){
                BigDecimal rechargeTotalAmount = userFundsMapper.getTotalAmountByUserIdIn7Day(userId,1);    //7天内充值金额
                if(rechargeTotalAmount.compareTo(BigDecimal.ZERO)==1) {
                    rs.setCode(10011);
                    rs.setMsg("提现失败，充值金额未消费，7日后方可提现。");
                    return rs;
                }
            }*/
            String key = DRAWCASH+userId;
            String value = stringRedisTemplate.opsForValue().get(key);
            if(StrUtils.isNotEmpty(value)){
                rs.setCode(10012);
                rs.setMsg("你还有未处理的提现，请稍后操作！");
                return rs;
            }
            try{
                //提现
                stringRedisTemplate.opsForValue().set(key,key);
                Long cashId = ymlConfig.getPkId();
                boolean flag = userFundsService.saveDrawCash(userInfoPO, money, payWay, payAccount,cashId);
                if(flag){
                    userMsgService.saveUserMsg(userInfoPO.getId(),String.format(msg_deposit,money),2);
                    if(payWay == 1){
                        rs = alipayService.saveTransferMoney(userId, cashId, money, payAccount);
                    }else if(payWay == 6){
                        rs = userWechatService.saveTransferMoney(request,userId, cashId, money, payAccount);
                    }
                }
                else{
                    userMsgService.saveUserMsg(userInfoPO.getId(),String.format(msg_deposit_error,money),2);
                    rs.setCode(10015);
                    rs.setMsg("提现失败！");
                    return rs;
                }
            }catch(Exception e){
                log.error(userId+"提现失败",e);
            }finally {
                stringRedisTemplate.delete(key);
            }
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL_100005.getCode());
            rs.setMsg(CodeEnum.FAIL_100005.getMsg());
            log.error("UserCash Page  Error:",e);
            return rs;
        }
        return rs;
    }


    /**
     * 提现审核
     * @param cashId
     * @param status 0 拒绝 1同意
     * @param auditUser 审核人
     * @param failNotes 原因
     * @return
     */
    @PostMapping("/auditDrawCash")
    public Result auditDrawCash(Long cashId, Integer status, String auditUser, String failNotes){
        Result rs = new Result();
        try{
            if(cashId == null || status == null){
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
                return rs;
            }
            UserCashPO cashPO = userCashService.selectById(cashId);
            if(cashPO == null){
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
                return rs;
            }
            if(status == 0){ // 拒绝：修改余额、修改状态
                userFundsService.saveDrawCashFail(cashId,cashId, failNotes, cashPO.getPay_amount());
            } else if(status == 1){//同意：支付宝转账
                userFundsService.saveDrawCashSuccess(cashId);
            } else {
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
                return rs;
            }
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL_100005.getCode());
            rs.setMsg(CodeEnum.FAIL_100005.getMsg());
            log.error("UserCash Page  Error:",e);
        }
        return rs;
    }


    /**
     * 中奖
     * @param userId
     * @param money
     * @return
     */
    @PostMapping("/winning")
    public Result winning(Long userId, BigDecimal money, Long orderId){
        Result rs = new Result();
        try{
            if(userId == null || money == null ){
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
            } else {
                userFundsService.saveRechargeOrConsume(userId, money, 3, 99, null, null);
            }
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL_100005.getCode());
            rs.setMsg(CodeEnum.FAIL_100005.getMsg());
            log.error("UserCash Page  Error:",e);
        }
        return rs;
    }
}
